package com.nebula.controller.salary;

import com.alibaba.fastjson.JSON;
import com.nebula.common.Const;
import com.nebula.common.DataGridFooter;
import com.nebula.common.PageResult;
import com.nebula.common.Result;
import com.nebula.controller.BaseController;
import com.nebula.entity.Benefits;
import com.nebula.service.IBenefitsService;
import com.nebula.service.ISalaryService;
import com.nebula.service.impl.BenefitsServiceImpl;
import com.nebula.service.impl.SalaryServiceImpl;
import com.nebula.util.DateTimeUtil;
import com.nebula.vo.BenefitsVo;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@SuppressWarnings("checkstyle:Indentation")
@WebServlet(name = "HolidayBenefitsController", urlPatterns = "/holidayBenefits")
public class HolidayBenefitsController extends BaseController {

    private final ISalaryService salaryService = new SalaryServiceImpl();

    private final IBenefitsService benefitsService = new BenefitsServiceImpl();

    public String index(HttpServletRequest request, HttpServletResponse response) {
        String navId = request.getParameter("id");
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        if (salaryService.checkNavRole(user.getRoleId(), navId)) {
            return Const.FORWARD + Const.DEFAULT_URL + "salary/holiday-benefits.jsp";
        } else {
            return Const.FORWARD + "role-error.jsp";
        }
    }

    public String findByUserId(HttpServletRequest request, HttpServletResponse response) {
        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        String size = request.getParameter("rows");
        String page = request.getParameter("page");
        if (StringUtils.isBlank(size)) {
            size = Const.SIZE;
        }
        if (StringUtils.isBlank(page)) {
            page = Const.PAGE;
        }
        int year = Integer.parseInt(request.getParameter("year"));
        PageResult<BenefitsVo> pageResult = benefitsService.findByUserIdAndPage(user.getId(), Integer.parseInt(page), Integer.parseInt(size), year);
        Map<String, Object> map = new HashMap<>();
        map.put("total", pageResult.getTotalCount());
        map.put("rows", pageResult.getList());

        DataGridFooter dataGridFooter = benefitsService.findTotalBenefits(user.getId(), year);
        List<BenefitsVo> benefitsVos = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            BenefitsVo benefitsVo = new BenefitsVo();
            if (i == 0) {
                benefitsVo.setRemark("当前页合计：");
                benefitsVo.setSalary(pageResult.getCurrTotalSalary());
            } else {
                benefitsVo.setRemark("总计：");
                benefitsVo.setSalary(dataGridFooter.getTotalSalary());
            }
            benefitsVos.add(benefitsVo);
        }
        map.put("footer", benefitsVos);
        return Const.JSON + JSON.toJSONString(map);
    }

    public String findById(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        BenefitsVo benefitsVo = benefitsService.findById(id);
        return Const.JSON + JSON.toJSONString(benefitsVo);
    }

    public String save(HttpServletRequest request, HttpServletResponse response) {
        String issueDate = request.getParameter("issueDate");
        String salary = request.getParameter("salary");
        String remark = request.getParameter("remark");
        if (StringUtils.isBlank(issueDate) || StringUtils.isBlank(salary) || StringUtils.isBlank(remark)) {
            return null;
        }
        //切割issueDate获取年月
        String[] split = issueDate.split("-");

        UserVo user = (UserVo) request.getSession().getAttribute(Const.USER_INFO);
        Benefits benefits = new Benefits();
        benefits.setIssueDate(DateTimeUtil.strToDate(issueDate, "yyyy-MM-dd"));
        benefits.setRemark(remark);
        benefits.setSalary(new BigDecimal(salary));
        benefits.setIssueYear(Integer.parseInt(split[0]));
        benefits.setIssueMonth(Integer.parseInt(split[1]));
        benefits.setUserId(user.getId());
        Date date = new Date();
        benefits.setCreatedTime(date);
        benefits.setUpdatedTime(date);
        try {
            benefitsService.save(benefits);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("添加成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("添加失败"));
        }
    }

    public String update(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        String issueDate = request.getParameter("issueDate");
        String salary = request.getParameter("salary");
        String remark = request.getParameter("remark");
        if (StringUtils.isBlank(issueDate) || StringUtils.isBlank(salary) || StringUtils.isBlank(remark)) {
            return null;
        }
        //切割issueDate获取年月
        String[] split = issueDate.split("-");

        Benefits benefits = new Benefits();
        benefits.setId(id);
        benefits.setIssueDate(DateTimeUtil.strToDate(issueDate, "yyyy-MM-dd"));
        benefits.setRemark(remark);
        benefits.setSalary(new BigDecimal(salary));
        benefits.setIssueYear(Integer.parseInt(split[0]));
        benefits.setIssueMonth(Integer.parseInt(split[1]));
        Date date = new Date();
        benefits.setUpdatedTime(date);
        try {
            benefitsService.update(benefits);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("保存失败"));
        }
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        try {
            benefitsService.delete(id);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("删除失败"));
        }
    }
}
